package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.RoleMapper;
import com.itheima.dao.MenuDao;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Result;
import com.itheima.service.MenuService;
import jdk.nashorn.internal.runtime.linker.LinkerCallSite;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @version V1.0
 * @author: sujiahao
 * @date: 2020/2/12 17:51
 * @description:
 */
@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements  MenuService{

    @Autowired
    private MenuDao menuDao;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void add(Menu menu) {
        if (menu.getParentMenuId() == 0){
            menu.setParentMenuId(null);
        }
            menuDao.add(menu);
    }

    @Override
    public void deleteById(Integer id) {
        menuDao.deleteById(id);
        menuDao.deleteByparentMenuId(id);
    }

    @Override
    public Menu queryById(Integer id) {
        Menu list = menuDao.queryById(id);
        return list;
    }

    @Override
    public void updataById(Menu menu) {
        menuDao.updataById(menu);
    }


    @Override
    public List<Menu> findMenu() {
       List<Menu> list = menuDao.findAll();
        List<Menu> one = new ArrayList<>();
        for (Menu menu : list) {
            if (menu.getParentMenuId() == null ){
                one.add(menu);
            }
        }
        for (Menu menu : one) {
            menu.setChildren(menuRecursion(menu.getId(),list));
        }

        return one;
    }



    private List<Menu> menuRecursion(Integer id,List<Menu> list) {
        List<Menu> childList = new ArrayList<>();
        for (Menu menu : list) {
            if (id.equals(menu.getParentMenuId())) {
                childList.add(menu);
            }
        }
        for (Menu menu : childList) {
            menu.setChildren(menuRecursion(menu.getId(), list));
        }


        return childList;
    }




    @Override
    public Result findByRoleId(String username) {
        //根据用户名查询角色id
        Integer id = roleMapper.findByRoleId(username);
        //查询次角色对应的一级菜单
        List<Menu> menuList = roleMapper.findOneMenu(id);
        for (Menu menu:menuList) {
            List<Menu> menuList1 = roleMapper.findTwoMenu(id,menu.getId());
            menu.setChildren(menuList1);
        }
        return new Result(true,"",menuList);

    }
}
